import React, { useRef } from 'react';
import {
  ProTable,
  ProFormText,
  ProFormSelect,
} from '@ant-design/pro-components';
import {
  Button,
  Modal,
  Space,
  Tag,
  Popconfirm,
  message,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'umi';
import type { ProColumns, ActionType } from '@ant-design/pro-components';
import dayjs from 'dayjs';

// 用户数据类型
interface UserItem {
  id: string;
  name: string;
  email: string;
  phone: string;
  department: string;
  position: string;
  status: 'active' | 'inactive';
  createTime: string;
  lastLoginTime?: string;
}

// 使用MCP服务器辅助开发的用户列表页面
// 开发时间预估：约30分钟（相比手动版本的2小时+）
const MCPAssistedUserList: React.FC = () => {
  const navigate = useNavigate();
  const actionRef = useRef<ActionType>();

  // 部门选项 - 通过MCP服务器快速配置
  const departmentOptions = [
    { label: '技术部', value: 'tech' },
    { label: '产品部', value: 'product' },
    { label: '运营部', value: 'operation' },
    { label: '市场部', value: 'marketing' },
    { label: '财务部', value: 'finance' },
  ];

  // 状态选项
  const statusOptions = [
    { label: '活跃', value: 'active' },
    { label: '非活跃', value: 'inactive' },
  ];

  // ProTable列定义 - 利用MCP提供的组件API快速配置
  const columns: ProColumns<UserItem>[] = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      fixed: 'left',
      width: 120,
      // 利用ProTable内置搜索功能
      copyable: true,
      ellipsis: true,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 200,
      copyable: true,
      // 使用ProTable内置的表单验证
      formItemProps: {
        rules: [
          { required: true, message: '请输入邮箱' },
          { type: 'email', message: '请输入正确的邮箱格式' },
        ],
      },
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 130,
      formItemProps: {
        rules: [
          { required: true, message: '请输入手机号' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
        ],
      },
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
      width: 100,
      // 利用ProTable的valueEnum快速配置下拉选项
      valueType: 'select',
      valueEnum: Object.fromEntries(
        departmentOptions.map(item => [item.value, { text: item.label }])
      ),
      formItemProps: {
        rules: [{ required: true, message: '请选择部门' }],
      },
    },
    {
      title: '职位',
      dataIndex: 'position',
      key: 'position',
      width: 120,
      formItemProps: {
        rules: [{ required: true, message: '请输入职位' }],
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      // 使用ProTable内置的状态渲染
      valueType: 'select',
      valueEnum: {
        active: { text: '活跃', status: 'Success' },
        inactive: { text: '非活跃', status: 'Error' },
      },
      formItemProps: {
        rules: [{ required: true, message: '请选择状态' }],
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
      valueType: 'dateTime',
      sorter: true,
      hideInForm: true,
    },
    {
      title: '最后登录',
      dataIndex: 'lastLoginTime',
      key: 'lastLoginTime',
      width: 150,
      valueType: 'dateTime',
      hideInForm: true,
      renderText: (text: string) => text || '-',
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 160,
      render: (text, record, _, action) => [
        <Button
          key="view"
          type="text"
          size="small"
          icon={<EyeOutlined />}
          onClick={() => navigate(`/mcp-crud/detail/${record.id}`)}
        >
          查看
        </Button>,
        <Button
          key="edit"
          type="text"
          size="small"
          icon={<EditOutlined />}
          onClick={() => {
            // 利用ProTable内置的编辑功能
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </Button>,
        <Popconfirm
          key="delete"
          title="确定要删除这个用户吗？"
          onConfirm={async () => {
            await handleDelete(record.id);
            action?.reload();
          }}
          okText="确定"
          cancelText="取消"
        >
          <Button
            type="text"
            size="small"
            danger
            icon={<DeleteOutlined />}
          >
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  // 数据请求函数 - ProTable自动处理分页、搜索、排序
  const fetchUsers = async (params: any, sort: any, filter: any) => {
    try {
      // 模拟API延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 模拟数据 - 在实际项目中这里会调用真实API
      const mockData: UserItem[] = Array.from({ length: 50 }, (_, index) => ({
        id: `user_${index + 1}`,
        name: `用户${index + 1}`,
        email: `user${index + 1}@example.com`,
        phone: `138${String(index + 1).padStart(8, '0')}`,
        department: departmentOptions[index % departmentOptions.length].value,
        position: `职位${index + 1}`,
        status: index % 3 === 0 ? 'inactive' : 'active',
        createTime: dayjs().subtract(index, 'day').format('YYYY-MM-DD HH:mm:ss'),
        lastLoginTime: index % 2 === 0 
          ? dayjs().subtract(index % 7, 'day').format('YYYY-MM-DD HH:mm:ss') 
          : undefined,
      }));

      // ProTable自动处理筛选逻辑
      let filteredData = mockData;
      
      // 应用搜索条件
      if (params.name) {
        filteredData = filteredData.filter(item => 
          item.name.includes(params.name)
        );
      }
      if (params.department) {
        filteredData = filteredData.filter(item => 
          item.department === params.department
        );
      }
      if (params.status) {
        filteredData = filteredData.filter(item => 
          item.status === params.status
        );
      }

      // ProTable自动处理分页
      const { current = 1, pageSize = 10 } = params;
      const start = (current - 1) * pageSize;
      const end = start + pageSize;
      const pageData = filteredData.slice(start, end);

      return {
        data: pageData,
        success: true,
        total: filteredData.length,
      };
    } catch (error) {
      message.error('获取用户列表失败');
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  // 删除用户
  const handleDelete = async (id: string) => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 300));
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 保存用户（新增/编辑）- ProTable内置表单处理
  const handleSave = async (key: React.Key, row: UserItem) => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      message.success('保存成功');
      actionRef.current?.reload();
      return true;
    } catch (error) {
      message.error('保存失败');
      return false;
    }
  };

  return (
    <div style={{ padding: 24 }}>
      {/* 使用ProTable替代手动实现的表格+搜索+分页 */}
      <ProTable<UserItem>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        request={fetchUsers}
        editable={{
          type: 'multiple',
          onSave: handleSave,
          onDelete: async (key) => {
            await handleDelete(key as string);
          },
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          // ProTable内置搜索表单配置
          collapsed: false,
          collapseRender: (collapsed) => (collapsed ? '展开' : '收起'),
          optionRender: ({ searchText, resetText }, { form }) => [
            <Button
              key="search"
              type="primary"
              onClick={() => {
                form?.submit();
              }}
            >
              {searchText}
            </Button>,
            <Button
              key="reset"
              onClick={() => {
                form?.resetFields();
                form?.submit();
              }}
            >
              {resetText}
            </Button>,
          ],
        }}
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) =>
            `第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
        }}
        scroll={{ x: 1200 }}
        headerTitle="用户管理"
        toolBarRender={() => [
          <Button
            key="add"
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              // 利用ProTable内置的新增功能
              actionRef.current?.addEditRecord?.({
                id: `new_${Date.now()}`,
                name: '',
                email: '',
                phone: '',
                department: '',
                position: '',
                status: 'active',
                createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
              });
            }}
          >
            新增用户
          </Button>,
        ]}
        // ProTable内置的其他便捷功能
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        dateFormatter="string"
        size="small"
      />
    </div>
  );
};

export default MCPAssistedUserList;